import Cookies from 'js-cookie'

const TokenKey = 'Web-User-Token'

export function getToken() {
    return Cookies.get(TokenKey)
}

export function setToken(token) {
    let attrs = {expires: 7, path: '/', domain: '.pipi.com'}
    return Cookies.set(TokenKey, token, attrs)
}

export function removeToken() {
    let attrs = {expires: 0, path: '/', domain: '.pipi.com'}
    return Cookies.remove(TokenKey, attrs)
}

export function setUserInfo(userInfo) {
    Object.entries(userInfo).forEach(([key, value]) => {
        // 确保 value 不是 null，并且不是 token
        if (value !== null && key !== 'token') {
            localStorage.setItem(key, JSON.stringify(value));
        }
    });
}

export function removeUserInfo(userInfo) {
    if (userInfo && typeof userInfo === 'object') {
        Object.keys(userInfo).forEach(key => {
            localStorage.removeItem(key);
        });
    } else {
        // 如果 userInfo 不传或不是对象，清空 localStorage
        localStorage.clear();
    }
}

export function getUserInfo() {
    const userInfo = {};
    // 遍历 localStorage 中的所有键
    Object.keys(localStorage).forEach(key => {
        // 获取值并解析 JSON
        const value = localStorage.getItem(key);
        userInfo[key] = JSON.parse(value);
    });
    return userInfo;
}


